import { _decorator, Button, Component, Label, labelAssembler, Node, ParticleSystem2D, Sprite, SpriteFrame, tween, v3 } from 'cc';
import { LayerBase } from './LayerBase';
import { UserInfo } from './UserInfo';
import { convertNumber, randomNum } from '../utils/utils';
import { StartSceneGameMgr } from './StartSceneGameMgr';
import { UILayerMgr } from './UILayerMgr';
import { Adsdk } from '../Adsdk';
import { loading } from '../loading';
import { qualityEnum, rewardEnum } from '../Enum';
import { AudioMgr } from '../utils/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('ShopPanel')
export class ShopPanel extends LayerBase {

    @property(Label)
    hasCrystalLabel:Label
    @property(Label)
    hasCoinLabel:Label
    @property(Label)
    freeBoxBtnLabel:Label;
    @property(Label)
    crystalSpaceNumLabel:Label
    @property([SpriteFrame])
    boxSps:SpriteFrame[]=[]
    @property(Node)
    openBoxEffectRoot:Node
    @property([Button])
    boxBtn:Button[]=[];
    @property(Label)
    useEpicBoxKeyBtnLabel:Label;
    @property(Label)
    uselegendBoxKeyBtnLabel:Label;
    
    private isAlreadyClickBoxBtn=false;//是否已经点击了宝箱按钮，避免重复点击

    set IsAlreadyClickBoxBtn(value){
        if (value==this.isAlreadyClickBoxBtn) {
            return;
        }
        if (value == true) {
            this.scheduleOnce(() => {
                this.IsAlreadyClickBoxBtn = false;
                this.boxBtn[0].enabled = true;
                this.boxBtn[1].enabled = true;
                this.boxBtn[2].enabled = true;
                this.boxBtn[3].enabled = true;
            }, 1.2)
        }
        else{
            this.boxBtn[0].enabled=false;
            this.boxBtn[1].enabled=false;
            this.boxBtn[2].enabled=false;
            this.boxBtn[3].enabled=false;

        }
      
        this.isAlreadyClickBoxBtn=value;
    }

    get IsAlreadyClickBoxBtn(){
        return this.isAlreadyClickBoxBtn;
    }

    init(somedData?: any): void {
        this.useEpicBoxKeyBtnLabel.string=`${UserInfo.epicBoxKeyNum}/1`
        this.uselegendBoxKeyBtnLabel.string=`${UserInfo.legendBoxKeyNum}/1`
        this.IsAlreadyClickBoxBtn=false;
        this.hasCrystalLabel.string=convertNumber(UserInfo.crystalMun);
        this.hasCoinLabel.string=convertNumber(UserInfo.coinMun);
        this.freeBoxBtnLabel.string=`免费 (${UserInfo.openFreeBoxNum}/${StartSceneGameMgr.ins.freeBoxOpenTotalNum})`
        this.crystalSpaceNumLabel.string="今日剩余次数："+(StartSceneGameMgr.ins.seeAdvGetCrystalTotalNum-UserInfo.seeAdvGetCrystalUseNum);
    }

    getFreeBoxReward(){
        let equipRandCount = randomNum(1, 100);
        let petChipRandCount = randomNum(1, 100);
        let roleChipRandCount = randomNum(1, 100);//获得角色碎片类型的概率
        let roleRandCount = randomNum(1, 100);//是否获得角色的概率,获得了角色就不获得角色碎片
        let getEquipQualityType=0;
        let getPetQualityType=0;
        let getEndSkillPropType=0;
        let getEndSkillPropNum=0;
        let getPetChipNum=0;
        let getCoinNum=randomNum(10,30);
        let getRoleChipOrRoleQualityType=0;
        let getRoleChipNum=0;
        let isGetRole=false;

        if (UserInfo.openFreeBoxNum>=5) {//一天抽五次免费宝箱，必中史诗级装备
            getEquipQualityType=2
        }
        else{
            if (0 < equipRandCount && equipRandCount < 60) {//普通,60%
                getEquipQualityType=0
            }
            else if (60 <= equipRandCount && equipRandCount < 85) {//稀有,25%
                getEquipQualityType=1
            }
            else if (85 <= equipRandCount && equipRandCount < 98) {//史诗,13%
                getEquipQualityType=2
            }
            else if(98 <= equipRandCount && equipRandCount <= 100){//传说,2%
                getEquipQualityType=3
            }
        }

        getEndSkillPropType=randomNum(0,2);
        getEndSkillPropNum=randomNum(1,3);
        getPetChipNum=randomNum(2,5);
        getRoleChipNum=randomNum(1,4);

        if (0 < petChipRandCount && petChipRandCount < 60) {//普通,60%
            getPetQualityType=0
        }
        else if (60 <= petChipRandCount && petChipRandCount < 85) {//稀有,25%
            getPetQualityType=1
        }
        else if (85 <= petChipRandCount && petChipRandCount < 98) {//史诗,13%
            getPetQualityType=2
        }
        else if(98 <= petChipRandCount && petChipRandCount <= 100){//传说,2%
            getPetQualityType=3
        }

        if (0 < roleChipRandCount && roleChipRandCount < 60) {//普通,60%
            getRoleChipOrRoleQualityType=0
        }
        else if (60 <= roleChipRandCount && roleChipRandCount < 85) {//稀有,25%
            getRoleChipOrRoleQualityType=1
        }
        else if (85 <= roleChipRandCount && roleChipRandCount < 98) {//史诗,13%
            getRoleChipOrRoleQualityType=2
        }
        else if(98 <= roleChipRandCount && roleChipRandCount <= 100){//传说,2%
            getRoleChipOrRoleQualityType=3
        }
        
        if (0 < roleRandCount && roleRandCount < 96) {//获得角色碎片,96%
            isGetRole=false;
        }
        else if (96 <= roleRandCount && roleRandCount <= 100) {//不获得角色碎片，直接获得角色,25%
            isGetRole=true;
        }
        
        let qualityEquipCongfiArr=[];
        UserInfo.equipCongfiDic.getValueList().forEach(element => {
            if (element.quality==getEquipQualityType) {
                qualityEquipCongfiArr.push(element)
            }
        });

        let getEquipCongfi=qualityEquipCongfiArr[randomNum(0,qualityEquipCongfiArr.length-1)];

        let qualityPetCongfiArr=[];
        UserInfo.petCongfiDic.getValueList().forEach(element => {
            if (element.quality==getPetQualityType) {
                qualityPetCongfiArr.push(element)
            }
        });

        let getPetCongfi = qualityPetCongfiArr[randomNum(0, qualityPetCongfiArr.length - 1)];

        let qualityRoleCongfiArr=[];
        UserInfo.roleCongfiDic.getValueList().forEach(element => {
            if (element.quality==getRoleChipOrRoleQualityType) {
                qualityRoleCongfiArr.push(element)
            }
        });

        let getRoleCongfi = qualityRoleCongfiArr[randomNum(0, qualityRoleCongfiArr.length - 1)];

        if (isGetRole) {
            StartSceneGameMgr.ins.getRole(getRoleCongfi.roleType);
            getRoleCongfi.count=1;
        }
        else {
            UserInfo.hasRoleChipArr[getRoleCongfi.roleType] += getRoleChipNum;
            getRoleCongfi.name=getRoleCongfi.name+"碎片"
            getRoleCongfi.count=getRoleChipNum;

        }
        StartSceneGameMgr.ins.getEquip(getEquipCongfi.equipType);
        let newNum = UserInfo.hasPetChipArr[getPetCongfi.petType] + getPetChipNum;
        UserInfo.hasPetChipArr[getPetCongfi.petType] = newNum;

        UserInfo.openFreeBoxNum += 1;
        UserInfo.todayOpenBoxNum += 1;
        UserInfo.coinMun += getCoinNum;
        UserInfo.hasEndSkillPropArr[getEndSkillPropType] += getEndSkillPropNum;
        StartSceneGameMgr.ins.saveGameDate();
        UILayerMgr.getIns.resfreshUI(this.node.name);

        getEquipCongfi.count = 1;
        getPetCongfi.count = getPetChipNum;
        getPetCongfi.name = getPetCongfi.name+"碎片";

        let endSkillPropData = UserInfo.rewardCongfiDic.get(getEndSkillPropType+3);
        endSkillPropData.count=getEndSkillPropNum;
        let coinData=UserInfo.rewardCongfiDic.get(rewardEnum.coin);
        coinData.count=getCoinNum;
        let rewardData=[getEquipCongfi,getRoleCongfi,endSkillPropData,getPetCongfi,coinData]
        this.generateOpenBoxEffect(0,rewardData);
    }

    getshishiBoxReward(){
        let getEndSkillPropType=0;
        let getEndSkillPropNum=0;
        let getPetChipNum=0;
        let getCoinNum=randomNum(20,40);
        let getRoleChipNum=0;
        let isGetRole=false;
        let roleRandCount=randomNum(1,100)

        getEndSkillPropType=randomNum(0,2);
        getEndSkillPropNum=randomNum(1,3);
        getPetChipNum=randomNum(2,5);
        getRoleChipNum=randomNum(2,6);

        if (0 < roleRandCount && roleRandCount < 96) {//获得角色碎片,96%
            isGetRole=false;
        }
        else if (96 <= roleRandCount && roleRandCount <= 100) {//不获得角色碎片，直接获得角色,25%
            isGetRole=true;
        }
        

        let qualityEquipCongfiArr=[];
        UserInfo.equipCongfiDic.getValueList().forEach(element => {
            if (element.quality==2) {
                qualityEquipCongfiArr.push(element)
            }
        });

        let qualityPetCongfiArr=[];
        UserInfo.petCongfiDic.getValueList().forEach(element => {
            if (element.quality==2) {
                qualityPetCongfiArr.push(element)
            }
        });

        let qualityRoleCongfiArr=[];
        UserInfo.roleCongfiDic.getValueList().forEach(element => {
            if (element.quality==qualityEnum.shishi) {
                qualityRoleCongfiArr.push(element)
            }
        });

        let getRoleCongfi = qualityRoleCongfiArr[randomNum(0, qualityRoleCongfiArr.length - 1)];
        let getPetCongfi=qualityPetCongfiArr[randomNum(0,qualityPetCongfiArr.length-1)];
        let getEquipCongfi=qualityEquipCongfiArr[randomNum(0,qualityEquipCongfiArr.length-1)];


        if (isGetRole) {
            StartSceneGameMgr.ins.getRole(getRoleCongfi.roleType);
            getRoleCongfi.count=1;
        }
        else {
            UserInfo.hasRoleChipArr[getRoleCongfi.roleType] += getRoleChipNum;
            getRoleCongfi.name=getRoleCongfi.name+"碎片"
            getRoleCongfi.count=getRoleChipNum;
        }
        UserInfo.todayOpenBoxNum+=1;
        UserInfo.coinMun+=getCoinNum;
        UserInfo.hasEndSkillPropArr[getEndSkillPropType]+=getEndSkillPropNum;
        let newNum = UserInfo.hasPetChipArr[getPetCongfi.petType] + getPetChipNum;
        UserInfo.hasPetChipArr[getPetCongfi.petType]=newNum;
        StartSceneGameMgr.ins.getEquip(getEquipCongfi.equipType);
        StartSceneGameMgr.ins.saveGameDate();
        UILayerMgr.getIns.resfreshUI(this.node.name);

        getEquipCongfi.count=1; 
        getPetCongfi.count=getPetChipNum;

        let endSkillPropData=UserInfo.rewardCongfiDic.get(getEndSkillPropType+3);
        endSkillPropData.count=getEndSkillPropNum;
        let coinData=UserInfo.rewardCongfiDic.get(rewardEnum.coin);
        coinData.count=getCoinNum;
        let rewardData=[getEquipCongfi,endSkillPropData,getPetCongfi,coinData,getRoleCongfi]
        this.generateOpenBoxEffect(1,rewardData);
    }

    getchuanshuoBoxReward() {
        let getEndSkillPropType = 0;
        let getEndSkillPropNum = 0;
        let getPetChipNum = 0;
        let getCoinNum = randomNum(30, 50);
        let getRoleChipNum=0;
        let isGetRole=false;
        let roleRandCount=randomNum(1,100)

        getEndSkillPropType = randomNum(0, 2);
        getEndSkillPropNum = randomNum(2, 4);
        getPetChipNum = randomNum(2, 5);
        getRoleChipNum=randomNum(4,8);

        if (0 < roleRandCount && roleRandCount < 96) {//获得角色碎片,96%
            isGetRole=false;
        }
        else if (96 <= roleRandCount && roleRandCount <= 100) {//不获得角色碎片，直接获得角色,25%
            isGetRole=true;
        }

        let qualityEquipCongfiArr = [];
        UserInfo.equipCongfiDic.getValueList().forEach(element => {
            if (element.quality == 3) {
                qualityEquipCongfiArr.push(element)
            }
        });

        let qualityPetCongfiArr=[];
        UserInfo.petCongfiDic.getValueList().forEach(element => {
            if (element.quality==3) {
                qualityPetCongfiArr.push(element)
            }
        });

        
        let qualityRoleCongfiArr=[];
        UserInfo.roleCongfiDic.getValueList().forEach(element => {
            if (element.quality==qualityEnum.chuanshuo) {
                qualityRoleCongfiArr.push(element)
            }
        });

        let getRoleCongfi = qualityRoleCongfiArr[randomNum(0, qualityRoleCongfiArr.length - 1)];
        let getPetCongfi=qualityPetCongfiArr[randomNum(0,qualityPetCongfiArr.length-1)];
        let getEquipCongfi = qualityEquipCongfiArr[randomNum(0, qualityEquipCongfiArr.length - 1)];

        
        if (isGetRole) {
            StartSceneGameMgr.ins.getRole(getRoleCongfi.roleType);
            getRoleCongfi.count=1;
        }
        else {
            UserInfo.hasRoleChipArr[getRoleCongfi.roleType] += getRoleChipNum;
            getRoleCongfi.name=getRoleCongfi.name+"碎片"
            getRoleCongfi.count=getRoleChipNum;
        }
        UserInfo.todayOpenBoxNum+=1;
        UserInfo.coinMun+=getCoinNum;
        let newNum = UserInfo.hasPetChipArr[getPetCongfi.petType] + getPetChipNum;
        UserInfo.hasPetChipArr[getPetCongfi.petType]=newNum;
        UserInfo.hasEndSkillPropArr[getEndSkillPropType]+=getEndSkillPropNum;
        StartSceneGameMgr.ins.getEquip(getEquipCongfi.equipType);
        StartSceneGameMgr.ins.saveGameDate();
        UILayerMgr.getIns.resfreshUI(this.node.name);

        getEquipCongfi.count=1; 
        getPetCongfi.count=getPetChipNum;

        let endSkillPropData=UserInfo.rewardCongfiDic.get(getEndSkillPropType+3);
        endSkillPropData.count=getEndSkillPropNum;
        let coinData=UserInfo.rewardCongfiDic.get(rewardEnum.coin);
        coinData.count=getCoinNum;
        let rewardData=[getEquipCongfi,endSkillPropData,getPetCongfi,coinData,getRoleCongfi]
        this.generateOpenBoxEffect(2,rewardData);
    }

    onclickFreeBoxRecieveBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (this.IsAlreadyClickBoxBtn==true) {
            console.log("不要重复点击")
            return;
        }
        this.IsAlreadyClickBoxBtn=true;
        if (UserInfo.openFreeBoxNum>=StartSceneGameMgr.ins.freeBoxOpenTotalNum) {
          StartSceneGameMgr.ins.createWidowTip("免费抽奖次数用完了，明天再来吧")  
        }
        else{
            Adsdk.instance.showVideo(()=>{
                AudioMgr.ins.playOneShot("audio/boxOpen",0.6);
                this.getFreeBoxReward();
            },()=>{

            })
        }
    }

    onclickshishiBoxRecieveBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (this.IsAlreadyClickBoxBtn == true) {
            return;
        }
        this.IsAlreadyClickBoxBtn = true;
        if (UserInfo.crystalMun >= 50) {
            UserInfo.crystalMun -= 50;
            AudioMgr.ins.playOneShot("audio/boxOpen",0.6);
            this.getshishiBoxReward();
        }
        else {
            StartSceneGameMgr.ins.createWidowTip("晶体不足");
        }


    }

    onclickchuanshuoBoxRecieveBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (this.IsAlreadyClickBoxBtn==true) {
            return;
        }
        this.IsAlreadyClickBoxBtn=true;
        if (UserInfo.crystalMun >= 120) {
            UserInfo.crystalMun -= 120;
            AudioMgr.ins.playOneShot("audio/boxOpen",0.6);
            this.getchuanshuoBoxReward();
        }
        else {
            StartSceneGameMgr.ins.createWidowTip("晶体不足");
        }
    }

    onclickCrystalAddBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        UILayerMgr.getIns.openUILayer("getCoinCrystalPanel");
    }

    onclickCrystalPackAgeBtn(){
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (this.IsAlreadyClickBoxBtn==true) {
            return;
        }
        this.IsAlreadyClickBoxBtn=true;

        if (UserInfo.seeAdvGetCrystalUseNum>=StartSceneGameMgr.ins.seeAdvGetCrystalTotalNum) {//使用完次数了
            StartSceneGameMgr.ins.createWidowTip("没有使用次数了每天再来吧");
        }
        else{
            Adsdk.instance.showVideo(()=>{
                let rewardCrystalNum=10;
                UserInfo.crystalMun+=rewardCrystalNum;
                UserInfo.seeAdvGetCrystalUseNum+=1;
                StartSceneGameMgr.ins.saveGameDate();
                StartSceneGameMgr.ins.createWidowTip(`获得${rewardCrystalNum}个晶体`);
                UILayerMgr.getIns.resfreshUI(this.node.name);
                UILayerMgr.getIns.resfreshUI("shopPanel")
            },()=>{
    
            })
        }
    }

    onclickUseEpicBoxKeyBtn(){
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (UserInfo.epicBoxKeyNum>=1) {
            UserInfo.epicBoxKeyNum-=1;
            this.getshishiBoxReward();
        }
        else{
            StartSceneGameMgr.ins.createWidowTip("钥匙不足")
        }
    }

    
    onclickUselegendBoxKeyBtn(){
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (UserInfo.legendBoxKeyNum>=1) {
            UserInfo.legendBoxKeyNum-=1;
            this.getchuanshuoBoxReward();
        }
        else{
            StartSceneGameMgr.ins.createWidowTip("钥匙不足")
        }
    }

    generateOpenBoxEffect(boxType, _getRewardData) {
        this.openBoxEffectRoot.active = true;
        let boxImgNode = this.openBoxEffectRoot.getChildByName("boxImg");
        boxImgNode.getComponent(Sprite).spriteFrame = this.boxSps[boxType]

        tween(boxImgNode)
            .to(0.1, { scale: v3(1.1, 1.1, 1) })
            .to(0.1, { scale: v3(0.9, 0.9, 1) })
            .to(0.1, { scale: v3(1.1, 1.1, 1) })
            .to(0.1, { scale: v3(0.9, 0.9, 1) })
            .to(0.1, { scale: v3(1, 1, 1) })
            .call(() => {
                this.openBoxEffectRoot.getChildByName("explodeParticle2D").getComponent(ParticleSystem2D).resetSystem()

                setTimeout(() => {
                    UILayerMgr.getIns.openUILayer("getRewardPanel", _getRewardData);
                    this.openBoxEffectRoot.getChildByName("explodeParticle2D").getComponent(ParticleSystem2D).stopSystem()
                    this.openBoxEffectRoot.active = false;
                }, 800)
            })
            .start()
    }

}


